//
//  HMPullDownRefreshController.swift
//  Weibo
//
//  Created by 米易雅克 on 16/4/21.
//  Copyright © 2016年 米易雅克. All rights reserved.
//

import UIKit
//刷新控件的高度
private let HMPullDownRefreshControlHeight: CGFloat = 60

//定义枚举类型
//下拉刷新的三种状态
enum HMPullDownRefreshControlStatus: Int {

    case Normal  //箭头朝下，  下拉刷新
    case PullToRefresh //箭头朝下，   释放刷新
    case Refreshing //正在刷新
}

//下拉刷新控件
class HMPullDownRefreshController: UIView {
//MARK: 属性
    //定义开始刷新闭包
    var pullDownRefreshHandler: (() -> ())?
    private var superScrollView: UIScrollView?
    
    //设置当前状态，默认下拉刷新，根据tableView.contentoffest.y值计算
    private var currentStatus: HMPullDownRefreshControlStatus = HMPullDownRefreshControlStatus.Normal {
        didSet {
        //当状态切换了，根据不同状态设置不同属性
            switch currentStatus {
            case .Normal:
                HMPrint("NOrmal")
                //隐藏转圈
                circleView.hidden = true
                //显示箭头
                arrowView.hidden = false
                
                //箭头回到初始位置，文字显示下拉刷新
                messageLabel.text = "下拉刷新"
                UIView.animateWithDuration(HMDefaultAnimationDur, animations: { 
                    self.arrowView.transform = CGAffineTransformIdentity
                })
            case .PullToRefresh:
                HMPrint("PullToRefresh")
                //箭头旋转，文字显示释放刷新
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(HMDefaultAnimationDur, animations: { 
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            
            case .Refreshing:
                HMPrint("Refreshing")
                //转圈文字显示 正在刷新。。。, 不要滚到导航栏下面
                messageLabel.text = "正在刷新..."
                //转圈
                circleView.hidden = false
                arrowView.hidden = true
                //添加动画(核心动画)
                let roationAnim = CABasicAnimation(keyPath: "transform.rotation")
                roationAnim.toValue = M_PI * 2
                roationAnim.repeatCount = MAXFLOAT
                roationAnim.duration = 0.5
                roationAnim.removedOnCompletion = false
                //给动画加forKey：如果下次在添加一个和之前已经存在的动画，先停止之前的动画在使用这次的动画，防止动画重复添加
                circleView.layer.addAnimation(roationAnim, forKey: "rotationAnim")
                //让tableView往下偏移HMPullDownRefreshControlHeight，刷新控件就不会被导航栏挡住
                UIView.animateWithDuration(HMDefaultAnimationDur, animations: { 
                    self.superScrollView?.contentInset.top += HMPullDownRefreshControlHeight
                })
                //调用闭包,告诉别人开始刷新
                pullDownRefreshHandler?()
            }
        }
    }
    //开始刷新
    func startRefreshing() {
    //将状态切换到refreshing
        currentStatus = .Refreshing
    
    }
    
    //完成刷新 切换到正常状态
    func endRefreshing() {
    currentStatus = .Normal
    //只有从refreshing切换normal才需要去contenInset.top - HMPullDownRefreshControlHeight
    //tableView 往上走HMPullDownRefreshControlHeight，就会隐藏刷新控件
        UIView.animateWithDuration(HMDefaultAnimationDur) { 
            self.superScrollView?.contentInset.top -= HMPullDownRefreshControlHeight
        }
    
    
    }
    
    override init(frame: CGRect) {
        //自己定义frame
        let newFrame = CGRect(x: 0, y: -HMPullDownRefreshControlHeight , width: UIScreen.mainScreen().bounds.width, height: HMPullDownRefreshControlHeight)
        
        super.init(frame: newFrame)
        //backgroundColor = UIColor.blueColor()
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//MARK: 添加子控价
    private func  prepareUI() {
    addSubview(arrowView)
    addSubview(circleView)
    addSubview(messageLabel)
    //隐藏转圈
    circleView.hidden = true
        
    //添加约束
    circleView.snp_makeConstraints { (make) in
        make.centerX.equalTo(self).offset(-30)
        make.centerY.equalTo(self)
        }
    //箭头
    arrowView.snp_makeConstraints { (make) in
        make.center.equalTo(circleView)
        }
    //显示文字
    messageLabel.snp_makeConstraints { (make) in
        make.leading.equalTo(circleView.snp_trailing).offset(10)
        make.centerY.equalTo(circleView)
        }
        
    }
    
    
    //当控件加到父控件里会调用这个方法，在这个时候可以拿到父控件
    //newSuperView 父控件
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        //判断父控件是UIScrollView或期子类
        if let scrollView = newSuperview as? UIScrollView {
            superScrollView = scrollView
            //kvo监听之改变
            // 要监听谁的属性,就用谁来调用
            // observer: 谁来处理监听事件
            // forKeyPath: 想监听的属性
            // options: 监听选项, 新值,老得值
            // context: 上下文

            superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        }
    }
    
    
    //移除kvo
    deinit {
            removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //实现kvo的监听方法,
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        HMPrint("tableView滚动了:\(superScrollView?.contentOffset.y)")
        
        
        // 用户拖拽才需要判断 Normal <==> PullToRefresh
        // dragging = 表示手在拖拽, false 松手了
        if superScrollView!.dragging {
            //切换normal 判断contentooffest.y还需要判断当前状态是pullToRefresh
            
            if currentStatus == .PullToRefresh && superScrollView?.contentOffset.y > -(superScrollView!.contentInset.top + HMPullDownRefreshControlHeight){
                HMPrint("切换到normal")
                currentStatus = .Normal
            }else if currentStatus == .Normal && superScrollView?.contentOffset.y < -(superScrollView!.contentInset.top + HMPullDownRefreshControlHeight) {
            
            HMPrint("切换到pullToreFresh")
                currentStatus = .PullToRefresh
            
            }
        }else if currentStatus == .PullToRefresh {
        //用户松手
            //刷新状态
            HMPrint("切换到Refreshing")
            currentStatus = .Refreshing
        
        }

    }
    
//MARK: 懒加载
    //箭头
    private lazy var arrowView: UIImageView = UIImageView(imageNamed: "tableview_pull_refresh")
    
    //转圈
    private lazy var circleView: UIImageView = UIImageView(imageNamed: "tableview_loading")
    
    //文字
    private lazy var messageLabel: UILabel = {
    
        let label = UILabel(fontSize: 14, textColor: UIColor.darkGrayColor())
        label.text = "下拉刷新"
        
        return label
    }()
    
   }
